<?php

namespace App\Http\Controllers;

abstract class Controller
{
    // 定义模型
    protected $model;

    // 定义构造器
    public function __construct()
    {
        $this->initialize();
    }

    // 定义初始化方法, 子类重写该方法即可保存模型
    protected function initialize() {}

    // 自定义成功响应方法
    protected function success($message = '操作成功', $data = [], $isObject = false)
    {
        $result = [
            'success' => true,
            'message' => $message,
            'data'    => $isObject ? (object)$data : $data
        ];

        return response($result);
    }

    // 自定义成功响应列表数据方法
    protected function successList($message = '获取成功', $list = [], $total = 0)
    {
        $result = [
            'success'   => true,
            'message'   => $message,
            'data'      => [
                'list'  => $list,
                'total' => $total
            ]
        ];
        return response($result);
    }

    // 自定义响应失败方法，422: 表示用户请求的数据无法处理
    protected function error($status = 422, $message = '操作失败', $data = [])
    {
        $result = [
            'success' => false,
            'message' => $message,
            'data'    => (object)$data
        ];
        return response($result, $status);
    }
}
